<template>
  <div>
    <!-- 卡片部分 -->
    <el-card class="jtqCard">
      <!-- 头部表单 -->
      <el-form ref="form" :model="form">
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="标签名称"
              label-width="70px"
              style="margin-right: 10px"
            >
              <el-input v-model="form.tags" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="城市"
              label-width="70px"
              style="margin-right: 10px"
            >
              <el-select
                style="width: 100%"
                v-model="form.province"
                placeholder="请选择"
                @change="changeCitys"
              >
                <el-option
                  v-for="(item, index) in selprovinces"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="地区"
              label-width="70px"
              style="margin-right: 10px"
            >
              <el-select
                style="width: 100%"
                v-model="form.city"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in selcitys"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称" label-width="70px">
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="状态"
              label-width="70px"
              style="margin-right: 10px"
            >
              <el-select
                style="width: 100%"
                v-model="form.state"
                placeholder="请选择"
              >
                <el-option
                  :value="item.value"
                  v-for="item in apiStatus"
                  :key="item.id"
                  >{{ item.value }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button style="margin-left: 25px" size="small" @click="clearAll"
              >清除</el-button
            >
            <el-button type="primary" size="small" @click="searchCompany"
              >搜索</el-button
            >
          </el-col>
          <el-button
            class="jtqBtn"
            icon="el-icon-edit"
            type="success"
            size="small"
            @click="editDo()"
            >新增用户</el-button
          >
        </el-row>
      </el-form>
      <!-- 提示组件 -->
      <Alert :total="sum" v-if="sum && sumFlag" />
      <!-- 列表部分 -->
      <el-table
        :data="list"
        style="width: 100%"
        :header-cell-style="headerStyle"
      >
        <el-table-column align="center" type="index" label="序号">
        </el-table-column>
        <el-table-column align="center" prop="number" label="企业编号">
        </el-table-column>
        <el-table-column align="center" prop="shortName" label="企业简称">
        </el-table-column>
        <el-table-column align="center" prop="tags" label="标签">
        </el-table-column>
        <el-table-column align="center" prop="creatorID" label="创建者">
        </el-table-column>
        <el-table-column align="center" prop="addDate" label="创建日期">
        </el-table-column>
        <el-table-column align="center" prop="remarks" label="备注">
        </el-table-column>
        <el-table-column align="center" prop="state" label="状态">
          <template v-slot="{ row }">
            {{ row.state === 0 ? '启动' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template v-slot="{ row }">
            <el-button
              circle
              plain
              type="primary"
              icon="el-icon-edit"
              @click="editDo(row)"
            ></el-button>
            <el-button
              circle
              plain
              :type="row.state === 0 ? 'warning' : 'success'"
              :icon="row.state === 0 ? 'el-icon-close' : 'el-icon-check'"
              @click="changeState(row.id, row.state)"
            >
            </el-button>
            <el-button
              circle
              plain
              type="danger"
              icon="el-icon-delete"
              @click="delData(row)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Pagination
        :page.sync="page"
        :pagesize.sync="pagesize"
        :total="sum"
        v-if="sum && sumFlag"
      />
    </el-card>
    <!-- 弹层部分 -->
    <el-dialog :visible="showDialog" :title="btnTitle" @close="isNo">
      <el-form
        ref="refForm"
        :model="dialogForm"
        label-width="160px"
        style="width: 510px"
        :rules="rules"
      >
        <el-form-item label="企业名称" prop="shortName">
          <el-input v-model="dialogForm.shortName"></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="dialogForm.company"></el-input>
          <p>https://www.tianyancha.com（在此可查询所属公司全称及简称）</p>
        </el-form-item>
        <el-form-item label="城市地区" required>
          <el-col :span="12">
            <el-form-item prop="province" style="margin-right: 10px">
              <el-select
                v-model="dialogForm.province"
                placeholder="请选择"
                style="width: 100%"
                @change="changeCitys"
              >
                <el-option
                  v-for="(item, index) in selprovinces"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="city">
              <el-select
                v-model="dialogForm.city"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in selcitys"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="方向（企业标签）" prop="company">
          <el-input v-model="dialogForm.tags"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="company">
          <el-input v-model="dialogForm.remarks" type="textarea"></el-input>
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="9">
            <el-button style="margin-left: 25px" size="small" @click="isNo"
              >取消</el-button
            >
            <el-button type="primary" size="small" @click="isOk"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Alert from './../../components/Jtq/alert'
import Pagination from './../../components/Jtq/pagination'
import { list, disabled, add, update, remove } from './../../api/hmmm/companys'
import { provinces, citys } from './../../api/hmmm/citys'
import baseApi from './../../api/base/baseApi'
export default {
  name: 'Permissions',
  data () {
    return {
      // 接受点击编辑或新增是初始变量
      initRow: null,
      // 弹框表单数据
      dialogForm: {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: '',
        isFamous: true
      },
      // 弹框表单验证规则
      rules: {
        shortName: [
          { required: true, message: '企业简称不能为空', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '所属公司不能为空', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        tags: [{ required: true, message: '请输入标签', trigger: 'blur' }],
        remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },
      btnTitle: '',
      showDialog: false,
      apiStatus: [],
      selprovinces: [], // 省市数据
      selcitys: [], // 城市数组
      list: [],
      page: 1,
      pagesize: 10,
      sum: null,
      sumFlag: false,
      // 头部表单数据
      form: {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      }
    }
  },
  created () {
    // 调用数据列表接口
    this.listData()
    // 获取省市
    this.selprovinces = provinces()
    // 获取状态常量
    this.apiStatus = baseApi.status
  },
  components: {
    Alert,
    Pagination
  },
  watch: {
    page () {
      this.listData()
    },
    pagesize () {
      this.listData()
    }
  },
  methods: {
    // 删除事件
    async delData (row) {
      // 弹框
      this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.sumFlag = false
          await remove({ id: row.id })
          this.sumFlag = true
          this.$message({
            type: 'success',
            message: '成功删除了用户!'
          })
          this.listData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 点击弹框确定触发
    async isOk () {
      await this.$refs.refForm.validate()
      if (this.initRow === undefined) {
        try {
          this.sumFlag = false
          await add(this.dialogForm)
          this.sumFlag = true
          this.$message.success('添加成功')
        } catch (e) {
          this.$message.error('添加失败')
          console.log(e)
        }
      } else {
        delete this.initRow.username
        if (this.initRow.isFamous === 1) {
          this.initRow.isFamous = true
        } else {
          this.initRow.isFamous = false
        }
        try {
          this.sumFlag = false
          await update({ ...this.initRow, ...this.dialogForm })
          this.sumFlag = true
          this.$message.success('编辑成功')
        } catch (e) {
          this.$message.error('编辑失败')
          console.log(e)
        }
      }
      // 调用数据列表接口
      this.listData()
      this.isNo()
    },
    // 点击弹框取消触发
    isNo () {
      this.initRow = null
      // 表单重置
      this.$refs.refForm.resetFields()
      // 表单数据重置
      this.dialogForm = {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: '',
        isFamous: true
      }
      this.showDialog = false
    },
    // 点击新增和编辑
    editDo (row) {
      if (row && row.id) {
        // 编辑
        this.btnTitle = '编辑用户'
      } else {
        // 新增
        this.btnTitle = '创建用户'
      }
      this.initRow = row
      if (this.initRow !== undefined) {
        this.dialogForm = this.initRow
      }
      this.showDialog = true
    },
    // 搜索按钮点击事件
    searchCompany () {
      this.sumFlag = false
      this.listData()
    },
    // 清除按钮点击事件
    clearAll () {
      this.form = {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      }
    },
    // 下拉菜单值改变时触发
    changeCitys () {
      this.selcitys = citys(this.form.province)
      this.form.city = this.selcitys[0]
      this.selcitys = citys(this.dialogForm.province)
      this.dialogForm.city = this.selcitys[0]
    },
    // 按钮点击事件——修改状态
    changeState (id, state) {
      let altext = ''
      if (state === 1) {
        altext = '启动'
      } else {
        altext = '禁用'
      }
      // 弹框
      this.$confirm(`已成功${altext}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const changeState = state === 0 ? 1 : 0
          // 修改数据状态接口
          await disabled({ id: id, state: changeState })
          this.$message({
            type: 'success',
            message: `已成功${altext}!`
          })
          this.listData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 列表表头样式回调
    headerStyle () {
      return { backgroundColor: '#f5f7fa' }
    },
    // 数据列表接口
    async listData () {
      const abc = {}
      for (const item in this.form) {
        this.form[item] !== '' && (abc[item] = this.form[item])
      }
      const {
        data: { counts, items }
      } = await list({ page: this.page, pagesize: this.pagesize, ...abc })
      this.sum = counts
      this.sumFlag = true
      this.list = items
    }
  }
}
</script>

<style scoped lang="less"></style>
